﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Utils;
using Settings;
using System.Data.SqlClient;

namespace SMSROUTER.Business
{
    public partial class SysUser
    {
        /// <summary>
        /// Kiểm tra user đăng nhập có phải là admin không
        /// </summary>
        /// <returns></returns>
        public bool IsRootAdmin()
        {
            return this.UserName.Equals(Constants.AdminRootAccount, StringComparison.CurrentCultureIgnoreCase);
        }

        /// <summary>
        /// Kiểm tra user name đã tồn tại trong hệ thống chưa
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static bool CheckExistUser(string userName)
        {
            using (var context = new DBDataContext(AppSetting.ConnectionString))
            {
                return context.SysUsers.Any(p => p.UserName == userName);
            }
        }

        public List<SysGroup> GetGroup()
        {
            using (var context  = new DBDataContext(AppSetting.ConnectionString))
            {
                return context.ExecuteQuery<SysGroup>(string.Format("SELECT * FROM SysGroup sg WHERE sg.GroupID IN (SELECT GroupID FROM SysUserGroup WHERE UserID = {0})", this.UserID)).ToList();
            }
        }

        public static SysUser Login(string userName, string password)
        {
            try
            {
                using (var context = new DBDataContext(AppSetting.ConnectionString))
                {
                    return context.SysUsers.FirstOrDefault(p => p.UserName == userName && p.Password == password.ToMD5Hash());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static SysUser GetByID(int id)
        {
            using (var context = new DBDataContext(AppSetting.ConnectionString))
            {
                return context.SysUsers.FirstOrDefault(p => p.UserID == id);
            }
        }

        public static string GetName(object id)
        {
            try
            {
                return GetByID(Convert.ToInt32(id)).UserName;
            }
            catch
            {
                return "Tài khoản này không tồn tại hoặc đã bị xóa";
            }
        }

        public static string GetGroupName(object id)
        {
            try
            {
                using (var context = new DBDataContext(AppSetting.ConnectionString))
                {
                    var userGroup = context.SysUsers.FirstOrDefault(p => p.UserID == Convert.ToInt32(id)).SysUserGroups;
                    return string.Join(", ", userGroup.Select(p => p.SysGroup.GroupName));
                            
                }
            }
            catch
            {
                return "";
            }
        }

        public static List<SysUser> GetAll()
        {
            using (var context = new DBDataContext(AppSetting.ConnectionString))
            {
                return context.SysUsers.Where(p => p.Deleted == false).ToList();
            }
        }

        public static List<SysUser> GetAll(string userName, int? groupId, bool? disabled)
        {
            using (var context = new DBDataContext(AppSetting.ConnectionString))
            {
                var result = context.SysUsers.Where(p => p.Deleted == false);
                if (!string.IsNullOrWhiteSpace(userName))
                {
                    result = result.Where(p => p.UserName == userName);
                }
                if (groupId != null)
                {
                    result = result.Where(p => p.SysUserGroups.Any(g => g.GroupID == groupId.Value && g.UserID == p.UserID));
                }
                if (disabled != null)
                {
                    result = result.Where(p => p.Disabled == disabled.Value);
                }
                return result.ToList();
            }
        }

        /// <summary>
        /// Lấy danh sách user để phân nhóm.
        /// </summary>
        /// <param name="GroupID"></param>
        /// <returns></returns>
        public static List<UserStructure> GetAllToSetGroup(int GroupID)
        {
            using (SqlConnection conn = new SqlConnection(AppSetting.ConnectionString))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                    SELECT su.*, CAST(1 AS BIT) Selected FROM SysUser su 
	                WHERE su.UserID IN (SELECT UserID FROM SysUserGroup WHERE GroupID = @GroupID)
	                UNION ALL
	                SELECT su.*, CAST(0 AS bit) Selected FROM SysUser su 
	                WHERE su.UserID NOT IN (SELECT UserID FROM SysUserGroup WHERE GroupID = @GroupID)
	                ORDER BY UserName";
                    cmd.Parameters.AddWithValue("@GroupID", GroupID);
                    return ObjectClass.CreateList<UserStructure>(cmd.ExecuteReader());
                }
            }
        }
    }
}
